<?php
/**
 * Created by PhpStorm.
 * User: ivi
 * Date: 2019/2/19
 * Time: 22:30
 */

namespace App\Utils;

use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Facades\Log;

/**
 * 返回对象
 * Class Output
 * @package App\Utils
 */
class Output implements Jsonable
{
    public $code = 0;
    public $msg = 'success';
    public $data = '';

    /**
     * 分页
     * @param $data
     * @param int $total
     * @param array $summary
     * @return Output
     */
    static function pager($data, $total, $summary = array())
    {
        $inc = new Output();
        $inc->data = $data;
        $inc->count = $total;
        if ($summary) {
            $inc->summary = $summary;
        }
        return $inc;
    }

    /**
     * 成功
     * @param $msg
     * @param array $data
     * @return Output
     */
    static function success($msg='OK', $data = [])
    {
        $inc = new Output();
        $inc->msg = $msg;
        $inc->data = $data;
        return $inc;
    }

    /**
     * 失败
     * @param $msg
     * @param int $code
     * @param array $data
     * @return Output
     */
    static function fail($msg, $code = -1, $data = [])
    {
        $inc = new Output();
        $inc->code = $code;
        $inc->msg = $msg;
        $inc->data = $data;
        return $inc;
    }

    /**
     * 异常
     * @param \Exception $e
     * @param $msg
     * @param int $code
     * @return Output
     */
    static function error($e, $msg, $code = -1)
    {
        Log::info($msg . ':' . $e->getMessage() . "\r\n" . $e->getTraceAsString());
        $inc = new Output();
        $inc->code = $code;
        $inc->msg = $msg;
        $inc->data = $e->getMessage();
        return $inc;
    }

    static function data($data,$msg='success')
    {
        $inc = new Output();
        $inc->data = $data;
        $inc->msg = $msg;
        return $inc;
    }

    /**
     * 设置统计
     * @param $data
     * @param array $fields
     * @return Output
     */
    function setSummary($data, $fields)
    {
        if (!empty($data)) {
            foreach ($fields as $field => $value) {
                $fields[$field] = $data[$field];
            }
            $this->count = $data['total'];
        } else {
            $this->count = 0;
        }
        $this->summary = $fields;
        return $this;
    }

    /**
     * 是否成功
     * @return bool
     */
    function isSuccess()
    {
        return $this->code == 0;
    }

    /**
     *
     *是否异常
     * @return bool
     */
    function isError()
    {
        return $this->code != 0;
    }

    function __toString()
    {
        return json_encode($this);
    }

    /**
     * Convert the object to its JSON representation.
     *
     * @param int $options
     * @return string
     */
    function toJson($options = 0)
    {
        return json_encode($this, $options);
    }

}
